//
//  MyInfoViewController.m
//  Article
//
//  Created by Haricot_cpc17 on 16/4/21.
//  Copyright © 2016年 mac. All rights reserved.
//
//个人资料
#import "MyInfoViewController.h"
#import "PassWordViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "LoginViewController.h"
#import "UIView+Toast.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "UIKit+AFNetworking.h"
#import "AFNetworking.h"
#import "AccountViewController.h"

@interface MyInfoViewController () <UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)UIImageView *headImageView;//头像
@property (nonatomic,strong)UIImagePickerController *myPicker;
@property (nonatomic,strong)UILabel *nameLabel;//昵称

@property (nonatomic,strong)AFHTTPRequestOperationManager *manager;

@property (nonatomic,strong)NSMutableDictionary *dataDic;

@property (nonatomic,strong)UITextField *nameText;//昵称

@end

@implementation MyInfoViewController{
    NSMutableDictionary *_alipay_numDic;
    int back;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self LoadThisPageData];
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
    
}
-(void)viewDidDisappear:(BOOL)animated{
    if (self.returnInfoBlock != NULL) {
        self.returnInfoBlock(_headImageView.image,_nameText.text,back);
    }
}
#pragma mark 传递个人信息给首页的block方法
-(void)returnInfoBlock:(ReturnInfoBlock)block{
    self.returnInfoBlock = block;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArray = [NSMutableArray array];
    _dataDic = [[NSMutableDictionary alloc]init];
    _alipay_numDic = [[NSMutableDictionary alloc]init];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:18],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(MYColor)];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:15 *MYWIDTH],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    self.navigationItem.title = @"个人资料";
    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(MYColor)];
    
    [self createUI];
    
    
    // Do any additional setup after loading the view.
}
//获取会员资料
-(void)LoadThisPageData{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{
                          @"user_token":[user objectForKey:@"token"]};
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:USER_INFO_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            [_alipay_numDic setValue:[[responseObject objectForKey:@"data"] objectForKey:@"truename"] forKey:@"truename"];
            [_alipay_numDic setValue:[[responseObject objectForKey:@"data"] objectForKey:@"wx_num"] forKey:@"wx_num"];
            [_alipay_numDic setValue:[[responseObject objectForKey:@"data"] objectForKey:@"alipay_num"] forKey:@"alipay_num"];
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}


-(void)save{
    NSLog(@"保存");
    
    back = 0;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSUserDefaults *user = [[NSUserDefaults alloc]init];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[NSString stringWithFormat:@"%@",_nameText.text] forKey:@"nickname"];

    for (NSString * key in _alipay_numDic) {

        if ([[_alipay_numDic objectForKey:key] length] > 0) {
            [dic setValue:[_alipay_numDic objectForKey:key] forKey:key];
        }
    }
    
    [manager POST:USER_EDIT_INFO_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString * str = [NSString stringWithFormat:@"%@",[dic objectForKey:@"status"]];
        if ([str isEqualToString:@"1"]) {
            [_tableView reloadData];
            
            [self.view makeToast:dic[@"info"] duration:0.5 position:CSToastPositionCenter];
            
            [user setObject:dic[@"data"][@"nickname"] forKey:@"nickname"];

            NSLog(@"保存成功");
            
        }else{
            [self.view makeToast:dic[@"info"] duration:0.5 position:CSToastPositionCenter];
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"%@",error.description);
              //       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
              [self.view makeToast:@"网络连接失败,请检查网络连接" duration:0.5 position:CSToastPositionCenter];
          }];
    
}
-(void)back{
    if (back == 1) {
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"您是否需要保存修改" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * aa = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [ac dismissViewControllerAnimated:YES completion:nil];
            
            [self save];
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        UIAlertAction *other = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        [ac addAction:other];
        [ac addAction:aa];
        [self presentViewController:ac animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];

    }
    
    
    
}
-(void)createUI{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MyInfoID"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = UIColorFromRGB(0xffffff);
    
    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(50 *MYWIDTH, 400 *MYHEIGHT, 275 *MYWIDTH, 40 *MYHEIGHT)];
    exitBtn.backgroundColor = UIColorFromRGB(0xff6a6a);
    exitBtn.layer.cornerRadius = 5;
    [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    exitBtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14*MYWIDTH];
    [exitBtn addTarget:self action:@selector(exitClick:) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:exitBtn];
}
-(void)exitClick:(UIButton *)btn{
    NSLog(@"退出登录");
    UIAlertView * alertView =[[UIAlertView alloc]initWithTitle:@"注销当前账号?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}
#pragma mark -- 警告框delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:{
            NSLog(@"取消");
        }
            break;
        case 1:{
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            
            [manager POST:LOGOUT_URL parameters:[userDefaults objectForKey:@"uid"] success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
                if ([str isEqualToString:@"1"]) {
                    
                    //移除UserDefaults中存储的用户信息
                    [userDefaults removeObjectForKey:@"uid"];
                    
                    [userDefaults removeObjectForKey:@"mobile"];
                    [userDefaults removeObjectForKey:@"password"];
                    [userDefaults removeObjectForKey:@"token"];
                    [userDefaults removeObjectForKey:@"nickname"];
                    
                    [userDefaults removeObjectForKey:@"sex"];
                    
                    [userDefaults removeObjectForKey:@"imageurl"];
                    //[userDefaults synchronize];
                    
                    NSLog(@"user %@",userDefaults);
                    
                    //  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注销成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    LoginViewController * loginVC =[[LoginViewController alloc]init];
                    [self presentViewController:loginVC animated:YES completion:nil];
                }
            }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@",error.description);
                [self.view makeToast:@"网络连接失败，请检查网络连接" duration:0.5 position:CSToastPositionCenter];
            }];
        }
            break;
        default:
            break;
    }
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUserDefaults *user = [[NSUserDefaults alloc]init];
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"MyInfoID"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = UIColorFromRGB(0xffffff);
    if (indexPath.row == 0) {
        cell.textLabel.text = @"头像";
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - WIDTH/4 - 10, 7 *MYHEIGHT, 70 *MYHEIGHT, 70 *MYHEIGHT)];
        _headImageView.layer.cornerRadius = 35 *MYHEIGHT;
        _headImageView.layer.masksToBounds = YES;
        _headImageView.userInteractionEnabled = YES;
        [_headImageView sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"imageurl"]] placeholderImage:[UIImage imageNamed:@"头像"]];
        [cell addSubview:_headImageView];
    }
    if (indexPath.row == 1) {
        cell.textLabel.text = @"手机号";
        
        cell.detailTextLabel.text = [user objectForKey:@"mobile"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.detailTextLabel.textColor = UIColorFromRGB(0x333333);
        cell.detailTextLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    }if (indexPath.row == 2) {
        cell.textLabel.text = @"昵称";
        _nameText = [[UITextField alloc]initWithFrame:CGRectMake(100 *MYWIDTH, 5, 245 *MYWIDTH, 40)];
        _nameText.textAlignment = NSTextAlignmentRight;
        _nameText.text = [user objectForKey:@"nickname"];
        _nameText.textColor = UIColorFromRGB(0x333333);
        _nameText.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
        [cell addSubview:_nameText];
        _nameText.delegate = self;
        
        
    }if (indexPath.row == 3) {
        cell.textLabel.text = @"修改密码";
        
    }if (indexPath.row == 4) {
        cell.textLabel.text = @"绑定账号";
        UILabel *nick = [[UILabel alloc]initWithFrame:CGRectMake(100 *MYWIDTH, 5, 245 *MYWIDTH, 40)];
        nick.textAlignment = NSTextAlignmentRight;
        if ([[_alipay_numDic objectForKey:@"truename"] length] == 0) {
            nick.text = @"未绑定";
        }else{
            nick.text = @"已绑定";
        }
        nick.textColor = UIColorFromRGB(0x333333);
        nick.font = [UIFont fontWithName:@"Heiti SC" size:13 *MYWIDTH];
        [cell addSubview:nick];
        
    }
    cell.textLabel.font = [UIFont fontWithName:@"Heiti SC" size:13*MYWIDTH];
    cell.textLabel.textColor = UIColorFromRGB(0x333333);
    return cell;
}
//点击return收起键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return true;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    back = 1;
    
    if (indexPath.row == 0) {
        //换头像
        UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //添加Button
        [alertSheet addAction: [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            //处理点击拍照
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                _myPicker = [[UIImagePickerController alloc] init];
                _myPicker.delegate = self;
                _myPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                _myPicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                _myPicker.allowsEditing = YES;
                [self presentViewController:_myPicker animated:YES completion:nil];
                NSLog(@"选择相机");
            }else{
                NSLog(@"不支持相机");
            }
        }]];
        [alertSheet addAction: [UIAlertAction actionWithTitle: @"从相册中选取" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            //处理点击从相册选取
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            {
                NSLog(@"支持图库");
                _myPicker = [[UIImagePickerController alloc] init];
                _myPicker.delegate = self;
                _myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                _myPicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                _myPicker.allowsEditing = YES;
                //[self presentModalViewController:_myPicker animated:YES];
                [self presentViewController:_myPicker animated:YES completion:nil];
                NSLog(@"选择相册");
            }
            //                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
            //                    {
            //                        NSLog(@"支持相片库");
            //                    }
            //                    [self presentViewController:_myPicker animated:YES completion:nil];
        }]];
        [alertSheet addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        
        [self presentViewController: alertSheet animated: YES completion: nil];
    }
    if (indexPath.row == 4) {
        AccountViewController *account = [[AccountViewController alloc]init];
        void(^aBlock)(NSMutableDictionary *dic) = ^(NSMutableDictionary *dic){
            _alipay_numDic = dic;
        };
        account.block = aBlock;
        account.upDataDic = [NSMutableDictionary dictionaryWithDictionary:_alipay_numDic];
        [self.navigationController pushViewController:account animated:YES];
    }
    if (indexPath.row == 3) {
        PassWordViewController *WeChatVC = [[PassWordViewController alloc]init];
        [self.navigationController pushViewController:WeChatVC animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 80;
    }else{
        return 50;
    }
}
#pragma mark imagePicker代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //取消选取图片
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"取消选取图片");
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    [_myPicker dismissViewControllerAnimated:YES completion:nil];
    
    _headImageView.image = [self fixOrientation:[info objectForKey:UIImagePickerControllerOriginalImage]];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    _headImageView.image = [self fixOrientation:[info objectForKey:UIImagePickerControllerOriginalImage]];
    
    //图片压缩
    NSData *imagedata = UIImageJPEGRepresentation(_headImageView.image, 0.1);
    
    NSString *urlstr = [NSString stringWithFormat:@"%@,%@",[user objectForKey:@"token"],[imagedata base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]];
    
    //NSLog(@"This is my photo%@",[imagedata base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]);
    
    //  NSLog(@"%@",urlstr);
    
    NSDictionary *dic = @{@"img":urlstr};
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [_manager POST:UPLOAD_AVATAR_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSDictionary *objdic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString *str = [objdic objectForKey:@"status"];
        
        NSDictionary *imagedic = [objdic objectForKey:@"data"];
        
        if (![str isEqual:@"1"]) {
            NSLog(@"上传成功");
            
            NSLog(@"%@",[imagedic objectForKey:@"avatar256"]);
            
            [user setObject:[imagedic objectForKey:@"avatar256"] forKey:@"imageurl"];
            
            [self clearChangeImage];
            
            [self.view makeToast:[objdic objectForKey:@"info"] duration:1.5 position:CSToastPositionCenter];
            
        }else{
            NSLog(@"上传失败");
            
            [self.view makeToast:[objdic objectForKey:@"info"] duration:1.5 position:CSToastPositionCenter];
            
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        //  [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSLog(@"上传失败");
        [self.view makeToast:@"上传失败" duration:1.5 position:CSToastPositionCenter];
    }];
    
}
//清除之前头像，下载新头像
-(void)clearChangeImage{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    [[[SDWebImageManager sharedManager]imageCache] clearDisk];
    [[[SDWebImageManager sharedManager]imageCache] clearMemory];
    
    [_headImageView sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"imageurl"]]];
    
}

#pragma mark 图片横屏
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    
    back = 1;
}







@end
